# -*- mode: snippet -*-
# name:  intercept $http
# group: angular
# key: ahttp
# --
angular.module('${1:myApp}').factory('${2:http}Injector', ['$q', function($q) {
  var regex1 = new RegExp('/api/articles/page/([0-9]+)');
  var regex2 = new RegExp('/dummy/test-articles.json.page=([0-9]+)');
  return {
    request: function(config) {
      // translate the URL from '/api/articles/page/0' to '/dummy/test-articles.json?page=0'
      if(config.url.match(regex1)) {
        config.url = '/dummy/test-articles.json?page='+config.url.match(regex1)[1];
      }
      return config;
    },
    requestError: function(resp) {
      return $q.reject(resp);
    },
    response: function(resp) {
      var pageId, pageSize = 2;
      if(resp.config.url.match(regex2)) {
        pageId = parseInt(resp.config.url.match(regex2)[1], 10);
        // slick the articles
        resp.data.articles = resp.data.articles.slice(pageId*pageSize, (pageId+1)*pageSize);
        // make sure the resp is JSON
        resp.headers()['content-type'] = 'application/json; charset=utf-8';
      return resp;
    },
    responseError: function (resp) {
      return $q.reject(resp);
    }
  };
}]).config(['$httpProvider', function($httpProvider) {
  $httpProvider.interceptors.push('${2:$(yas/substr yas-text "[^ ]*")}Injector');
}]);